package com.demo.ben.action;


import com.demo.ben.service.IModifyService;
import com.demo.ben.service.IQueryService;
import com.demo.spring.formework.annotation.QBAutowired;
import com.demo.spring.formework.annotation.QBController;
import com.demo.spring.formework.annotation.QBRequestMapping;
import com.demo.spring.formework.annotation.QBRequestParam;
import com.demo.spring.formework.webmvc.servlet.QBModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 公布接口url
 * @author Tom
 *
 *
 */
@QBController
@QBRequestMapping("/web")
public class MyAction {

    @QBAutowired
    IQueryService queryService;
    @QBAutowired
    IModifyService modifyService;

    @QBRequestMapping("/query.json")
    public QBModelAndView query(HttpServletRequest request, HttpServletResponse response,
                                @QBRequestParam("name") String name){
        String result = queryService.query(name);
        return out(response,result);
    }

    @QBRequestMapping("/add*.json")
    public QBModelAndView add(HttpServletRequest request,HttpServletResponse response,
                              @QBRequestParam("name") String name,@QBRequestParam("addr") String addr){
        String result = null;
        try {
            result = modifyService.add(name,addr);
            return out(response,result);
        } catch (Exception e) {
//			e.printStackTrace();
            Map<String,Object> model = new HashMap<String,Object>();
            model.put("detail",e.getMessage());
//			System.out.println(Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
            model.put("stackTrace", Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
            return new QBModelAndView("500",model);
        }

    }

    @QBRequestMapping("/remove.json")
    public QBModelAndView remove(HttpServletRequest request,HttpServletResponse response,
                                 @QBRequestParam("id") Integer id){
        String result = modifyService.remove(id);
        return out(response,result);
    }

    @QBRequestMapping("/edit.json")
    public QBModelAndView edit(HttpServletRequest request,HttpServletResponse response,
                               @QBRequestParam("id") Integer id,
                               @QBRequestParam("name") String name){
        String result = modifyService.edit(id,name);
        return out(response,result);
    }



    private QBModelAndView out(HttpServletResponse resp,String str){
        try {
            resp.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}